package com.xiaoq.shop.service.impl;

import com.xiaoq.shop.entity.UserCouponEntity;
import com.xiaoq.shop.repository.IUserCouponRepository;
import com.xiaoq.shop.service.IUserCouponService;
import com.xiaoq.shop.vo.UserCouponDetailVo;
import com.xiaoq.shop.vo.UserCouponVo;
import com.xiaoq.vo.PagingVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenjh on 2017/11/6.
 */
@Service
public class UserCouponServiceImpl implements IUserCouponService{

    @Autowired
    private IUserCouponRepository userCouponRepository;

    @Override
    public boolean lockUserCoupon(String userCouponId, String userId) {
        UserCouponEntity userCouponEntity = userCouponRepository.getUserCouponById(userCouponId);
        if(userCouponEntity == null || !StringUtils.equals(userCouponEntity.getUserId(), userId)){
            return false;
        }
        long currentMillis = System.currentTimeMillis();

        if(currentMillis > userCouponEntity.getExpirationDate()){
            if(userCouponEntity.getState() != UserCouponEntity.StateEnum.BEUSEED.value()
                    && userCouponEntity.getState() != UserCouponEntity.StateEnum.EXPIRED.value()){
                //设置优惠券为过期
                userCouponRepository.updateUserCoupon(userCouponId, userId, UserCouponEntity.StateEnum.EXPIRED.value());
                return false;
            }
        }

        if(currentMillis < userCouponEntity.getExpirationDate()
                && userCouponEntity.getEffectiveDate() < currentMillis
                && userCouponEntity.getState() == UserCouponEntity.StateEnum.NOUSE.value()){
            //锁定优惠券
            userCouponRepository.updateUserCoupon(userCouponId, userId, UserCouponEntity.StateEnum.LOCKED.value());
            return true;
        }

        return false;
    }

    @Override
    public boolean releaseUserCoupon(String userCouponId, String userId) {
        UserCouponEntity userCouponEntity = userCouponRepository.getUserCouponById(userCouponId);
        if(userCouponEntity == null || !StringUtils.equals(userCouponEntity.getUserId(), userId)){
            return false;
        }
        long currentMillis = System.currentTimeMillis();
        if(currentMillis < userCouponEntity.getExpirationDate()
                && userCouponEntity.getEffectiveDate() < currentMillis
                && userCouponEntity.getState()== UserCouponEntity.StateEnum.LOCKED.value()){
            //释放优惠券
            userCouponRepository.updateUserCoupon(userCouponId, userId, UserCouponEntity.StateEnum.NOUSE.value());
            return true;
        }else if(currentMillis > userCouponEntity.getExpirationDate()){
            if(userCouponEntity.getState() != UserCouponEntity.StateEnum.BEUSEED.value()
                    && userCouponEntity.getState() != UserCouponEntity.StateEnum.EXPIRED.value()){
                //设置优惠券为过期
                userCouponRepository.updateUserCoupon(userCouponId, userId, UserCouponEntity.StateEnum.EXPIRED.value());
                return true;
            }
        }
        return false;
    }

    @Override
    public UserCouponEntity getUserCouponById(String userCouponId) {
        return userCouponRepository.getUserCouponById(userCouponId);
    }

    @Override
    public UserCouponDetailVo getUserAllCouponList(String shopId, String userId) {
        UserCouponDetailVo userCouponDetailVo = null;
        if(StringUtils.isNotBlank(shopId)){
            List<UserCouponEntity> userCouponEntityList = userCouponRepository.getUserAllCouponList(shopId, userId);
            userCouponDetailVo = getUserCouponDetailVo(userCouponDetailVo, userCouponEntityList);
        }

        return userCouponDetailVo;
    }

    @Override
    public UserCouponDetailVo getUserAllCouponListByUserId(String userId) {
        UserCouponDetailVo userCouponDetailVo = null;
        List<UserCouponEntity> userCouponEntityList = userCouponRepository.getUserAllCouponList(null, userId);
        userCouponDetailVo = getUserCouponDetailVo(userCouponDetailVo, userCouponEntityList);
        return userCouponDetailVo;
    }

    private UserCouponDetailVo getUserCouponDetailVo(UserCouponDetailVo userCouponDetailVo, List<UserCouponEntity> userCouponEntityList) {
        List<UserCouponVo> unUsedCouponList = new ArrayList<>(); //未使用的优惠券
        List<UserCouponVo> expiredCouponList = new ArrayList<>(); //已失效的优惠券

        long currentMillis = System.currentTimeMillis();
        if(CollectionUtils.isNotEmpty(userCouponEntityList)){
            userCouponDetailVo = new UserCouponDetailVo();

            //对userCouponEntityList排序
            userCouponEntityList.forEach(userCoupon -> {
                int userCouponState = userCoupon.getState();
                if(userCouponState != UserCouponEntity.StateEnum.DELETE.value()){

                    if(userCoupon.getExpirationDate() < currentMillis){
                        //设置成已过期
                        userCoupon.setState(UserCouponEntity.StateEnum.EXPIRED.value());
                        expiredCouponList.add(transform2UserCouponVo(userCoupon));

                    }else if(userCouponState == UserCouponEntity.StateEnum.NOUSE.value()
                            && userCoupon.getEffectiveDate()<currentMillis
                            && userCoupon.getExpirationDate()>currentMillis){
                        unUsedCouponList.add(transform2UserCouponVo(userCoupon));

                    }else if(userCouponState != UserCouponEntity.StateEnum.LOCKED.value()){
                        expiredCouponList.add(transform2UserCouponVo(userCoupon));
                    }
                }
            });
            //对未使用的优惠券进行排序，距过期时间最短的排在最前面
            unUsedCouponList.sort((couponVo1, couponVo2)->{
                long expiredTime1 = couponVo1.getExpirationDate() - currentMillis;
                long expiredTime2 = couponVo2.getExpirationDate() - currentMillis;
                return (int)(expiredTime1 - expiredTime2);
            });

            userCouponDetailVo.setExpiredCouponList(expiredCouponList);
            userCouponDetailVo.setUnusedCouponList(unUsedCouponList);
        }
        //如果没有优惠券，返回空数据集合
        if(userCouponDetailVo == null){
            userCouponDetailVo = new UserCouponDetailVo();
            userCouponDetailVo.setUnusedCouponList(new ArrayList<>());
            userCouponDetailVo.setExpiredCouponList(new ArrayList<>());
        }
        return userCouponDetailVo;
    }

    private UserCouponVo transform2UserCouponVo(UserCouponEntity userCouponEntity){
        UserCouponVo userCouponVo = null;
        if(userCouponEntity != null){
            userCouponVo = new UserCouponVo();
            BeanUtils.copyProperties(userCouponEntity, userCouponVo);
            userCouponVo.setUserCouponId(userCouponEntity.getId());
        }
        return userCouponVo;
    }

    @Override
    public long getUserCouponCount(String userId) {
        return userCouponRepository.getUserCouponCount(userId);
    }

    @Override
    public boolean saveUserCoupon(UserCouponEntity userCouponEntity) {
        return userCouponRepository.save(userCouponEntity);
    }

    @Override
    public long getUserCouponCount(String userId, String couponInstanceCode) {
        return userCouponRepository.getUserCouponCount(userId, couponInstanceCode);
    }

    @Override
    public boolean updateUserCouponStatus(String userCouponId, String userId, int status) {
        if(StringUtils.isAnyBlank(userCouponId, userId)){
            return false;
        }
        return userCouponRepository.updateUserCoupon(userCouponId, userId, status);
    }

    @Override
    public boolean deleteUserCoupon(String userId, String userCouponId) {
        return userCouponRepository.updateUserCoupon(userCouponId, userId, UserCouponEntity.StateEnum.DELETE.value());
    }

    @Override
    public List<UserCouponEntity> getNotExpiredCouponList(String shopId, String userId) {
        return userCouponRepository.getNotExpiredCouponList(shopId, userId);
    }

    @Override
    public List<UserCouponEntity> getUserCouponList(String shopId, List<String> couponInstanceCodeList) {
        return userCouponRepository.getUserCouponList(shopId, couponInstanceCodeList);
    }

    /**
     * 定时任务用
     * @param couponInstanceCodeList 优惠券主键列表
     * @param pagingVo 分页参数
     * @return
     */
    @Override
    public List<UserCouponEntity> getUserCouponList4Schedule(List<String> couponInstanceCodeList, PagingVo pagingVo){
        return userCouponRepository.getUserCouponList4Schedule(couponInstanceCodeList, pagingVo);
    }
}